package com.maimao.info.service;

import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.core.utils.DateUtils;
import com.maimao.info.mapper.SearchHistoryMapper;
import com.maimao.model.info.SearchHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2020/12/29 9:39 下午
 */
@Service
public class SearchHistoryService {
    @Autowired
    private SearchHistoryMapper searchHistoryMapper;

    /**
     * 当前用户的历史记录信息 todo 添加redis
     */
    public List<SearchHistory> history(String userId) {
        return searchHistoryMapper.selectByUserId(userId);
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void addHistory(String key, String userId) {
        SearchHistory searchHistory = searchHistoryMapper.selectByKeyAndUserId(key, Long.valueOf(userId));
        if (searchHistory != null) {
            searchHistory.setCreateTime(DateUtils.now());
            searchHistoryMapper.updateById(searchHistory);
        } else {
            searchHistoryMapper.insert(new SearchHistory(Long.valueOf(userId), key, DateUtils.now()));
        }
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void deleteHistory(String key, String userId) {
        searchHistoryMapper.deleteByKeyAndUserId(key, userId);
    }
}
